import Dexie from "dexie";
//创建一个数据库 若数据库已存在则为打开
const SCHEMA = "&path";
/**
 * Indexed DB
 *  Datebase:
 *      Disks: fullPathString - Class File
 *      每张表是一个硬盘分区，存储不同的路径结构
 */
class DataBase {
    constructor(DataBaseName) {
        this.db = new Dexie(DataBaseName || "FileSystem");
    }
    version = 1;
    Disks = [];
    // 初始化数据库，只是导入以前的东西
    async initDataBase() {
        try {
            await this.db.open();
            this.version = this.db.verno;
            this.Disks = this.db._storeNames.reduce((col, Name) => {
                col[Name] = SCHEMA;
                return col;
            }, {});
            this.db.close();
            this.db.version(this.version).stores(this.Disks);
            return this.db.open();
        } catch (error) {
            this.db.close();
            console.log(error);
            if (error.name === "NoSuchDatabaseError") {
                this.Disks = {
                    C: SCHEMA,
                };
                this.db.version(1).stores(this.Disks);
                return this.db.open();
            }
            throw error;
        }
    }
    // 获取一个 Disk 内部的所有文件路径并结构化
    getStructure(DiskName) {
        return this.db[DiskName].toCollection().keys();
    }
    // 添加一张 Disk 表
    addDisk(DiskName) {
        this.db.close();
        this.Disks[DiskName] = SCHEMA;
        this.db.version(this.version + 1).stores(this.Disks);
        return this.db.open();
    }
    deleteDisk(DiskName) {
        return this.db[DiskName].clear();
    }

    moveFile(src, des) {
        const SRC = this.db[DiskNameSrc];
        const DES = this.db[DiskNameDes];
        await this.db.transaction("rw", [SRC, DESC], async () => {
            const files = await SRC.where("path").startsWith(src);
            const deleteCount = await DES.delete(src);
        });

        // return this.db[DiskName].update(src, {
        //     path: des,
        // });
    }
    // 文件操作
    writeFile(pathValue) {
        const DiskName = pathValue.replace(/^(\d+):\/\/.*?/, "$1");
        return this.db[DiskName].put(pathValue);
    }
    writeFiles(DiskName, pathValues) {
        return this.db[DiskName].bulkPut(pathValues);
    }
    readFile(DiskName, path) {
        return this.db[DiskName].getByKeyPath(path);
    }
    readFiles(DiskName, pathArray) {
        return this.db[DiskName].where("path")
            .anyOf(pathArray)
            .distinct() // 筛选掉重复的数据
            .toArray();
    }
    deleteFile(DiskName, path) {
        return this.db[DiskName].delete(path);
    }
    deleteFiles(DiskName, pathArray) {
        return this.db[DiskName].bulkDelete(pathArray);
    }

    deleteDir(DiskName, path) {
        return this.db[DiskName].where("path").startsWith(path).delete();
    }
}
const Storage = new DataBase();
await Storage.initDataBase();
export default Storage;
